package org.kobjects.isodate;

import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 * <p>Title: IsoDate </p>
 * <p>Description:  </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @version : 1.0
 * @date : 2023/11/21 15:20
 */
public class IsoDate {
 public static final int DATE = 1;
 public static final int TIME = 2;
 public static final int DATE_TIME = 3;

 public IsoDate() {
 }

 static void dd(StringBuffer buf, int i) {
  buf.append((char)(48 + i / 10));
  buf.append((char)(48 + i % 10));
 }

 public static String dateToString(Date date, int type) {
  Calendar c = Calendar.getInstance();
  c.setTimeZone(TimeZone.getTimeZone("GMT"));
  c.setTime(date);
  StringBuffer buf = new StringBuffer();
  int ms;
  if ((type & 1) != 0) {
   ms = c.get(1);
   dd(buf, ms / 100);
   dd(buf, ms % 100);
   buf.append('-');
   dd(buf, c.get(2) - 0 + 1);
   buf.append('-');
   dd(buf, c.get(5));
   if (type == 3) {
    buf.append("T");
   }
  }

  if ((type & 2) != 0) {
   dd(buf, c.get(11));
   buf.append(':');
   dd(buf, c.get(12));
   buf.append(':');
   dd(buf, c.get(13));
   buf.append('.');
   ms = c.get(14);
   buf.append((char)(48 + ms / 100));
   dd(buf, ms % 100);
   buf.append('Z');
  }

  return buf.toString();
 }

 public static Date stringToDate(String text, int type) {
  Calendar c = Calendar.getInstance();
  if ((type & 1) != 0) {
   c.set(1, Integer.parseInt(text.substring(0, 4)));
   c.set(2, Integer.parseInt(text.substring(5, 7)) - 1 + 0);
   c.set(5, Integer.parseInt(text.substring(8, 10)));
   if (type != 3 || text.length() < 11) {
    c.set(11, 0);
    c.set(12, 0);
    c.set(13, 0);
    c.set(14, 0);
    return c.getTime();
   }

   text = text.substring(11);
  } else {
   c.setTime(new Date(0L));
  }

  c.set(11, Integer.parseInt(text.substring(0, 2)));
  c.set(12, Integer.parseInt(text.substring(3, 5)));
  c.set(13, Integer.parseInt(text.substring(6, 8)));
  int pos = 8;
  if (pos < text.length() && text.charAt(pos) == '.') {
   int ms = 0;
   int f = 100;

   while(true) {
    ++pos;
    char d = text.charAt(pos);
    if (d < '0' || d > '9') {
     c.set(14, ms);
     break;
    }

    ms += (d - 48) * f;
    f /= 10;
   }
  } else {
   c.set(14, 0);
  }

  if (pos < text.length()) {
   if (text.charAt(pos) != '+' && text.charAt(pos) != '-') {
    if (text.charAt(pos) != 'Z') {
     throw new RuntimeException("illegal time format!");
    }

    c.setTimeZone(TimeZone.getTimeZone("GMT"));
   } else {
    c.setTimeZone(TimeZone.getTimeZone("GMT" + text.substring(pos)));
   }
  }

  return c.getTime();
 }
}